package com.wangsd.web.coupon.controller;

import com.wangsd.common.component.WxComponentService;
import com.wangsd.common.component.WxjavaService;
import com.wangsd.common.config.WxOpenProperties;
import com.wangsd.common.config.WxPayProperties;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.HttpUtil;
import com.wangsd.web.MyController;
import com.wangsd.web.coupon.entity.Company;
import com.wangsd.web.coupon.entity.ServiceBusiness;
import com.wangsd.web.coupon.service.CompanyService;
import com.wangsd.web.coupon.service.ServiceBusinessService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@Controller
@RequestMapping("/wxopen")
public class WxOpenController extends MyController {
    @Autowired
    WxjavaService wxjavaService;
    @Autowired
    WxComponentService wxComponentService;
    @Autowired
    CompanyService companyService;
    @Autowired
    ServiceBusinessService serviceBusinessService;

    @Value("${notify_url}")
    private String notify_url;

    /**
     * 开放平台第三方平台代公众号授权
     *
     * @param appid
     * @param scope
     * @param state      1授权服务商,2普通授权
     * @param from
     * @param miniOpenid 小程序网页授权服务商为了发优惠券
     */
    @GetMapping("/authorize")
    @ResponseBody
    public void authorize(String appid, String scope, String state, String from, String miniOpenid) {
        log.info("进入授权：" + appid);
        String userAgent = request.getHeader(HTTP.USER_AGENT);//"wechat","alipay","dingtalk"

        //如果是小程序授权，去查询服务商配置的appid
        if (miniOpenid != null) {
            Company company = companyService.selectByMiniAppid(appid);
            ServiceBusiness serviceBusiness = serviceBusinessService.getById(company.getBusinessServiceId());
            appid = serviceBusiness.getAppId();
        }

        from = notify_url +"/notify/memberAuthCallBack";

        try {
            String redirect = "https://wechat.alipayjf.com/api/open/authorize?appid="+appid
                    + "&from="+ from +"&state="+miniOpenid;
        /*String redirect = "http://wechat.alipayjf.com/api/open/authorize?appid="+appid+""
                + "&from="+notify_url+"/notify/memberAuthCallBack&state="+miniOpenid;*/
            response.sendRedirect(redirect);
//            HttpUtil.httpRequest(redirect);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/go")
    @ResponseBody
    public String gotoPreAuthUrlShow() {
        return "<a href='toAuth'>go</a>";
    }

    @GetMapping("/authGo")
    @ResponseBody
    public String authGo(Long businessServiceId) {
        return "<script>location.href ='toAuth?businessServiceId=" + businessServiceId + "'; </script>";
    }

    /**
     * 发起授权(公众号授权给第三方平台)
     *
     * @param businessServiceId
     */
    @GetMapping("/toAuth")
    public void toAuth(Long businessServiceId) {
        String redirect = notify_url + "/notify/authCallback/" + businessServiceId;
        try {
            String url = wxComponentService.getWxOpenComponentService().getPreAuthUrl(redirect);
            response.sendRedirect(url);
        } catch (IOException e) {
            log.error("IOException",e);
        } catch (WxErrorException e) {
            throw new BusinessException(e.getError().getErrorMsg());
        }
    }

}
